package org.example.audio;

/**
 * @author zehua
 * @date 2023/11/8 15:37
 * @Description TODO 音频比较 测试没差异
 * @since V1.1.0
 */
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;

public class AudioComparator {

    public static double compareAudio(String file1, String file2) throws Exception {
        FFmpegFrameGrabber grabber1 = new FFmpegFrameGrabber(file1);
        FFmpegFrameGrabber grabber2 = new FFmpegFrameGrabber(file2);

        grabber1.start();
        grabber2.start();

        Frame frame1;
        Frame frame2;

        double totalDifference = 0;
        int sampleCount = 0;

        while ((frame1 = grabber1.grabSamples()) != null && (frame2 = grabber2.grabSamples()) != null) {
            short[] samples1 = new short[frame1.samples[0].limit()];
            short[] samples2 = new short[frame2.samples[0].limit()];
            for (int i = 0; i < Math.min(samples1.length, samples2.length); i++) {
                totalDifference += Math.abs(samples1[i] - samples2[i]);
                sampleCount++;
            }
        }

        grabber1.stop();
        grabber2.stop();

        return sampleCount > 0 ? (1 - (totalDifference / sampleCount) / Short.MAX_VALUE) : 0;
    }

    public static void main(String[] args) throws Exception {
        String audioFile1 = "E:\\test\\video\\testAudio.mp3";
        String audioFile2 = "E:\\test\\video\\testAudio_2023-11-081655232.mp3";

        double similarity = compareAudio(audioFile1, audioFile2);
        System.out.println("Similarity: " + similarity);
    }
}
